'use strict';
const fs = require('fs-extra');
const p = require('path');
const md5 = require('md5');
const chp = require('child_process');
const promisify = require('util').promisify;
const exec = promisify(chp.exec);
const puppeteer = require('puppeteer');


// app.js 或 agent.js 文件：
class AppBootHook {
  constructor(app) {
    this.app = app;
  }

  configWillLoad() {
    // Ready to call configDidLoad,
    // Config, plugin files are referred,
    // this is the last chance to modify the config.
  }

  configDidLoad() {
    // Config, plugin files have been loaded.
  }

  async didLoad() {
    // All files have loaded, start plugin here.
  }

  async willReady() {
    // All plugins have started, can do some thing before app ready
  }

  async didReady() {
    let that = this;

    const browser = await puppeteer.launch({
      defaultViewport: {
        width: 1920, height: 1080
      },
      headless: 'new'
    });
    this.app.browser = browser;
    // 请将您的 app.ready 中的代码置于此处。
    this.app.messenger.on('test', dat => {
      console.log('test');
    });
    this.app.messenger.on('add-tv', job => {
      if (job.save_type == 'm3u8') {
        tvMu8Task(job);
      }
      if (job.save_type == 'mp4') {
        tvMp4Task(job);
      }
    });

    async function tvMu8Task(job) {
      let { idx, tv_id, play_name, source, tv_path, tv_name, ffmpeg_path } = job;
      let folder_name = md5(play_name)
        .substring(8, 24);
      let target_folder = p.join(tv_path, folder_name);
      if (!fs.pathExistsSync(target_folder)) {
        fs.mkdirSync(target_folder);
      }
      let target = p.join(target_folder, 'index.m3u8');
      let cmd = `${ffmpeg_path} -i ${source} -codec: copy  -start_number 0 -hls_time 10 -hls_list_size 0 -f hls ${target}`;
      await exec(cmd);
      await that.app.model.TeleplayList.create({
        tv_id,
        link: folder_name + '/index.m3u8',
        idx,
        play_name,
      });
      console.log(`任务 ${play_name} 完成`);
    }

    async function tvMp4Task(job) {
      let { idx, tv_id, play_name, source, tv_path, tv_name } = job;
      console.log('mp4 task', tv_name, idx);
      let file_name = md5(play_name)
        .substring(8, 24) + p.extname(source);
      let target = p.join(tv_path, file_name);
      let readStream = fs.createReadStream(source);
      let writeStream = fs.createWriteStream(target);
      readStream.pipe(writeStream);
      readStream.on('end', async () => {
        console.log('文件已经复制');
        await that.app.model.TeleplayList.create({
          tv_id,
          link: file_name,
          idx,
          play_name,
        });
        await  that.app.model.Notifi.create({
          title: "任务完成",
          content: `添加电视剧 ${play_name} 任务已完成`,
        });
        that.app.sseMessage({msg: `移动复制 ${play_name} 任务已完成`})
        console.log(`任务 ${play_name} 完成`);
      });
    }
  }

  async serverDidReady() {
    // Server is listening.
  }

  async beforeClose() {
    // Do some thing before app close.
  }

}

module.exports = AppBootHook;
